package ferp.android.social.twvk;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import ferp.android.social.Connector;
import ferp.core.game.Game;

/**
 * User: olegs
 * Date: 5/19/13 10:38 PM
 */
public abstract class TwVkConnector extends Connector
{
  @Override
  public boolean isLoggedIn(Activity owner)
  {
    Account a = loadAccount(owner);

    return a.accessToken != null;
  }

  @Override
  public void onActivityResult(Activity owner, int result, Intent intent)
  {
    // when login activity cancelled the intent is null
    if (result == Activity.RESULT_OK)
    {
      Account a = Game.gson.fromJson(intent.getExtras().getString(LoginActivity.BUNDLE_ACCOUNT), Account.class);

      saveAccount(owner, a);
    }

    if (loginListener != null)
      loginListener.onLoginFinished(getRequestCode(), result == Activity.RESULT_OK);
  }

  @Override
  public void logout(Activity owner)
  {
    doLogout(owner);

    // clear account data
    Account a = new Account();
    saveAccount(owner, a);
  }

  protected Account loadAccount(Activity owner)
  {
    SharedPreferences sp = owner.getSharedPreferences(Connector.SOCIAL, Context.MODE_PRIVATE);
    Account a = Game.gson.fromJson(sp.getString(ACCOUNT + getClass().getSimpleName(), null), Account.class);

    if (a == null)
      a = new Account();

    return a;
  }

  protected void saveAccount(Activity owner, Account a)
  {
    SharedPreferences sp = owner.getSharedPreferences(Connector.SOCIAL, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();

    editor.putString(ACCOUNT + getClass().getSimpleName(), Game.gson.toJson(a));
    editor.commit();
  }

  @Override
  protected void doLogin(Activity owner, int requestCode)
  {
    owner.startActivityForResult(new Intent(owner, getLoginActivityClass()), requestCode);
  }

  protected abstract Class getLoginActivityClass();

  protected abstract void doLogout(Activity owner);

  private final static String ACCOUNT = "account_";
}
